//
//  NoticeViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/5/13.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "NoticeViewController.h"
#import "CommonResponse.h"
#import <MBProgressHUD.h>
#import <MWPhotoProtocol.h>
#import "UITapImageView.h"
#import <TTTAttributedLabel.h>
#import <MBProgressHUD.h>

typedef NS_ENUM(NSInteger, TTTAttributedLabelType) {
    TTTAttributedLabelTypeNone,
    TTTAttributedLabelTypeUrl,
    TTTAttributedLabelTypePhone
};

@interface NoticeViewController ()<TTTAttributedLabelDelegate>{
    MBProgressHUD *HUD;
}

@property (nonatomic,strong)MWPhoto *photos;
@end

@implementation NoticeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    //[self setupViews];
    [self loadData];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self setupViews];
}

#pragma mark - 初始化视图
- (void)setupViews{
    if (self.viewType == KKView_Notice) {
        self.title = @"公告";
    }
    else {
        self.title = @"意见";
    }
    self.view.backgroundColor = [UIColor whiteColor];
    
    //适配iOS7uinavigationbar遮挡tableView的问题
    if(IS_IOS7)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    scrollView.bounces = NO;
    //水平进度条不显示
    scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:scrollView];
    
    //标题
    UILabel *title = [UILabel labelMultiLineFontSize:kListTitleFontSize content:self.titleStr labelWidth:kScreen_Width - 4*CELL_PADDING_LEFT];
    title.centerX = kScreen_Width/2;
    title.y = CELL_PADDING_TOP;
    [scrollView addSubview:title];
    
    //来源和时间
    UILabel *fromDate = [UILabel labelSingleLineFontSize:10 content:self.fromAndDateStr];
    fromDate.x = kScreen_Width - CELL_PADDING_RIGHT - fromDate.width;
    fromDate.y = CGRectGetMaxY(title.frame) + CELL_PADDING_TOP;
    fromDate.textColor = CM_PLACEHOLDER_TEXT_COLOR;
    [scrollView addSubview:fromDate];
    
    //内容
    CGSize size = [Tools sizeOfMultiLineText:self.contentStr withSize:kListDetailFontSize withWidth:kScreen_Width - 2*CELL_PADDING_LEFT];
    TTTAttributedLabel *content = [[TTTAttributedLabel alloc]initWithFrame:CGRectMake(CELL_PADDING_LEFT, CGRectGetMaxY(fromDate.frame) + CELL_PADDING_TOP, size.width, size.height + CELL_PADDING_BOTTOM)];
    content.width = kScreen_Width - 2*CELL_PADDING_LEFT;
    content.numberOfLines = 0;
    content.lineBreakMode = NSLineBreakByWordWrapping;
    content.font = [UIFont systemFontOfSize:kListDetailFontSize];
    //检测url
    content.enabledTextCheckingTypes = NSTextCheckingTypeLink;
    //对齐方式
    content.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
    [content setText:self.contentStr];
    
    // URL检测
    NSError *error;
    NSString *regulaStr = @"\\bhttps?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSArray *arrayOfAllMatches = [regex matchesInString:self.contentStr options:0 range:NSMakeRange(0, [self.contentStr length])];
    
    for (NSTextCheckingResult *match in arrayOfAllMatches) {
        NSString* substringForMatch = [self.contentStr substringWithRange:match.range];
        [self fillDataToLabel:content content:substringForMatch url:[NSURL URLWithString:substringForMatch] type:TTTAttributedLabelTypeUrl];
    }
    [scrollView addSubview:content];
    
    
    //图片
    NSString *url;
    if (self.viewType == KKView_Suggestion) {
        url = [NSString stringWithFormat:@"%@2.0/suggestionmanager.svc/viewpic?token=%@&id=%@", HTTP_HOST, [[AccountManager manager]token], self.guidId];
    }
    else {
        url = [NSString stringWithFormat:@"%@2.0/postmanager.svc/viewpic?token=%@&id=%@", HTTP_HOST, [[AccountManager manager]token], self.guidId];
    }
    NSURL *URL = [NSURL URLWithString:url];
    CGFloat y = CGRectGetMaxY(content.frame) + CELL_PADDING_TOP;
    UITapImageView *image = [[UITapImageView alloc]initWithFrame:CGRectMake(0, y, kScreen_Width, kScreen_Width)];
    image.contentMode = UIViewContentModeScaleAspectFit;
    
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.labelText = @"图片加载中...";
    
    [image sd_setImageWithURL:URL placeholderImage:nil completed:^(UIImage *img, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [HUD setHidden:YES];
        if (img != nil) {
            [image addTargetBlock:^(id obj) {
                MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
                
                // Set options
                browser.displayActionButton = NO; // Show action button to allow sharing, copying, etc (defaults to YES)
                browser.displayNavArrows = NO; // Whether to display left and right nav arrows on toolbar (defaults to NO)
                browser.displaySelectionButtons = NO; // Whether selection buttons are shown on each image (defaults to NO)
                browser.zoomPhotosToFill = YES; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
                browser.alwaysShowControls = NO; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
                browser.enableGrid = YES; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
                browser.startOnGrid = NO; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
                //        browser.wantsFullScreenLayout = YES; // iOS 5 & 6 only: Decide if you want the photo browser full screen, i.e. whether the status bar is affected (defaults to YES)
                
                // Optionally set the current visible photo before displaying
                [browser setCurrentPhotoIndex:1];
                
                // Present
                [self.navigationController pushViewController:browser animated:YES];
                
                // Manipulate
                //        [browser showNextPhotoAnimated:YES];
                //        [browser showPreviousPhotoAnimated:YES];
                //        [browser setCurrentPhotoIndex:1];
            }];
        }
    }];
    
    self.photos = [MWPhoto photoWithURL:[NSURL URLWithString:url]];
    
    image.centerX = kScreen_Width/2;
    [scrollView addSubview:image];
//    CGSize size;
    size.width = kScreen_Width;
    size.height = CGRectGetMaxY(image.frame) + CELL_PADDING_BOTTOM;
    scrollView.contentSize = size;
}

#pragma mark - 事件响应


#pragma mark - 图片浏览器代理
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return 1;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
//    if (index < self.photos.count)
//        return [self.photos objectAtIndex:index];
    return self.photos;
}


#pragma mark - 加载数据
/**
 *  初始化数据
 */
- (void)initData {
    
}

/**
 *  加载视图所有的数据
 */
- (void)loadData {
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -链接文本处理
/**
 *  填充数据到UILabel
 *
 *  @param label   UILabel
 *  @param title   标题
 *  @param content 内容
 */
- (void)fillDataToLabel:(TTTAttributedLabel *)label content:(NSString *)content url:(NSURL *)url type:(TTTAttributedLabelType)type{
    NSMutableAttributedString *contentStr = [[NSMutableAttributedString alloc] initWithString:content];
    [contentStr addAttributes:@{(__bridge NSString *)kCTForegroundColorAttributeName:CM_BLUE_COLOR} range:NSMakeRange(0, contentStr.length)];
    
    label.linkAttributes = kLinkAttributes;
    label.activeLinkAttributes = kLinkAttributesActive;
//    label.font = [UIFont boldSystemFontOfSize:13];
    
//    label.text = contentStr;
    label.textAlignment = NSTextAlignmentCenter;
    switch (type) {
        case TTTAttributedLabelTypePhone:{
            NSRange range = [label.text rangeOfString:content];
            [label addLinkToPhoneNumber:content withRange:range];
            label.delegate = self;
            break;
        }
        case TTTAttributedLabelTypeUrl:{
            NSRange range = [label.text rangeOfString:content];
            [label addLinkToURL:url withRange:range];
            label.delegate = self;
            break;
        }
        default:
            break;
    }
}


#pragma mark - TTAttributeLabel 代理
-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url{
    [[UIApplication sharedApplication] openURL:url];
}

-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithPhoneNumber:(NSString *)phoneNumber{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]]];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

